package com.mysiteforme.admin.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WX_UserUtil {

    @Autowired
    private WX_TokenUtil wX_TokenUtil;

    private static Logger logger = LoggerFactory.getLogger(WX_UserUtil.class);

    /**
     * 根据微信openId 获取用户是否订阅
     *
     * @param openId 微信openId
     * @return 是否订阅该公众号标识
     */
    public Response<Object> subscribeState(String openId) {
        AccessToken accessToken = wX_TokenUtil.getWXToken(openId);
        if (accessToken == null) {
            return ResponseUtils.returnCommonException("消息推送，获取微信Token失败");
        }
        String tmpurl = Constants.MESSAGE_PUSH_TOKEN + accessToken.getAccessToken() + "&openid=" + openId;
        JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "GET", null);
        JSONObject resultJson = new JSONObject(result);
        logger.error("获取用户是否订阅 errcode:{} errmsg:{}", resultJson.getInteger("errcode"), resultJson.getString("errmsg"));
        Integer errcode = (Integer) resultJson.get("errcode");
        String errmsg = (String) resultJson.get("errmsg");
        if (errcode != null) {
            if (Constants.ERROR_CODE_43004.equals(errcode.toString())) {
                return ResponseUtils.returnCommonException("该用户未关注本公众号openId" + openId);
            }
        }
        if (errmsg == null) {
            //用户是否订阅该公众号标识（0代表此用户没有关注该公众号 1表示关注了该公众号）。
            Integer subscribe = (Integer) resultJson.get("subscribe");
            logger.error("用户是否订阅该公众号标识（0代表此用户没有关注该公众号 1表示关注了该公众号）:" + subscribe);
            return ResponseUtils.returnObjectSuccess(true);
        }
        return ResponseUtils.returnCommonException(errmsg);
    }


    public JSONObject getUserInfo(String openId) {
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + wX_TokenUtil.getWXToken(openId).getAccessToken() + "&openid=" + openId;
        JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "GET", null);
        JSONObject resultJson = new JSONObject(result);
        logger.error("获取用户是否订阅 errcode:{} errmsg:{}", resultJson.getInteger("errcode"), resultJson.getString("errmsg"));
        String errmsg = (String) resultJson.get("errmsg");
        return resultJson;
    }
}
